<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="8" :lg="8" :md="8" :sm="24">
            <a-form-item label="产品名称">
              <a-input placeholder="请输入产品名称" v-model.trim="queryParam_.name"></a-input>
              <a-radio style="margin-left: 8px;" :checked="queryParam_.isViolation" @click="handleChange">不限违规</a-radio>
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24">
            <a-form-item label="SKU">
              <a-input placeholder="请输入" v-model="queryParam_.code"></a-input>
              <a-radio-group :default-value="1" name="radioGroup" style="margin-left: 8px; white-space: nowrap;" v-model="queryParam_.codeType">
                <a-radio :value="1">SPU</a-radio>
                <a-radio :value="2">SKU</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-item label="创建时间">
                <a-range-picker v-model="queryParam_.timeRange" @change="timeChange" show-time format="YYYY-MM-DD HH:mm:ss" style="width: 100%;" />
                <a-select style="margin-left: 8px;" v-model="queryParam_.timeRangeType" placeholder="创建时间" allowClear >
                  <a-select-option :value="1">创建时间</a-select-option>
                  <a-select-option :value="2">完成时间 </a-select-option>
                  <a-select-option :value="3">下架时间</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-item label="流程">
                <j-search-select-tag placeholder="请选择流程" v-model="queryParam_.productStatus" dict="product_status"/>
              </a-form-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-item label="产品类目" :labelCol="{xs: { span: 24 },sm: { span: 7 },}" :wrapperCol="{xs: { span: 24 },sm: { span: 16 },}">
                <a-tree-select
                  allow-clear
                  v-model="queryParam_.categoryId"
                  :replaceFields="replaceFields"
                  :filterTreeNode="filterTreeNode"
                  show-search
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="treeData"
                  placeholder="请选择产品类目"
                  tree-default-expand-all
                  :getPopupContainer="node => node.parentNode"
                  @change="handleCategoryIdChange"
                >
                </a-tree-select>
              </a-form-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-item label="开发专员">
                <j-search-select-user v-model="queryParam_.createBy" placeholder="请输入并选择开发专员"></j-search-select-user>
              </a-form-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24" v-has="'ProductLibrarySkuList:supplierName'">
              <a-form-item label="供应商名称">
                <a-input placeholder="请输入供应商名称" v-model.trim="queryParam_.supplierName"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-item label="产品标题">
                <a-input placeholder="请输入产品英文标题" v-model.trim="queryParam_.title"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-item label="状态">
                <a-select v-model="queryParam_.status" placeholder="请选择状态" >
                  <a-select-option :value="1">上架(完成)</a-select-option>
                  <a-select-option :value="2">停产下架(下架)</a-select-option>
                </a-select>
                <a-radio style="margin-left: 8px;" :checked="queryParam_.statusType === '1' ? true : false" @click="handleChange_">取反</a-radio>
              </a-form-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-item label="排序">
                <a-select v-model="queryParam_.orderType" placeholder="请选择排序" >
                  <a-select-option value="1">完成时间降序</a-select-option>
                  <a-select-option value="2">完成时间升序</a-select-option>
                  <a-select-option value="3">创建时间降序</a-select-option>
                  <a-select-option value="4">创建时间升序</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-item label="版型编码">
                <a-input placeholder="请输入版型编码" v-model.trim="queryParam_.patternCode"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="8" :lg="8" :md="8" :sm="24">
              <a-form-item label="特性标签">
                <j-multi-select-tag
                  placeholder="请选择特性标签"
                  v-model="queryParam_.tagIds"
                  :options="tagOptions"
                />
                <a-radio-group :default-value="1" name="radioGroup" style="margin-left: 8px; white-space: nowrap;" v-model="queryParam_.tagIdsType">
                  <a-radio :value="1">满足所有</a-radio>
                  <a-radio :value="2">取反</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <!-- <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button> -->
      <a-button type="primary" icon="download" @click="handleExportCustom" v-has="'ProductLibrarySkuList:export'">导出</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel" v-has="'ProductLibrarySkuList:MSKU'">
        <a-button type="primary" icon="import">MSKU导入</a-button>
      </a-upload>
      <a-button type="primary" icon="download" @click="handleExportXls('MSKU模版列表', url.exportMSKUTemplatesXls)" v-has="'ProductLibrarySkuList:exportMSKUTemplate'">MSKU模版导出</a-button>
      <j-multi-select-tag
        v-if="tagOptions_ && tagOptions_.length"
        style="width: 150px; margin-right: 8px;"
        v-has="'ProductLibrarySkuList:CharacteristicTag'"
        placeholder="特性标签"
        v-model="buttonTagIds"
        :options="tagOptions_"
        @blur="handleBlur"
      />
      <a-dropdown v-has="'ProductLibrarySkuList:UpperLowerFrame'">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="handleUpdateShelfStatus(1)">上架</a-menu-item>
          <a-menu-item key="2" @click="handleUpdateShelfStatus(2)">下架</a-menu-item>
        </a-menu>
        <a-button type="primary"> 上下架 <a-icon type="down" /> </a-button>
      </a-dropdown>
      <a-button type="primary" v-has="'ProductLibrarySkuList:inspectionTool'" @click="handleProductInspectionTool">产品检测工具</a-button>
      <a-dropdown>
        <a-menu slot="overlay">
          <a-menu-item v-for="d in dictOptions" :key="d.value" v-has="d.vHas" @click="handleProcessChange(d)">移到 {{ d.text }}</a-menu-item>
        </a-menu>
        <a-button type="primary"> 流程变更 <a-icon type="down" /> </a-button>
      </a-dropdown>
      <!-- 高级查询区域 -->
      <!-- <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query> -->
      <!-- <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown> -->
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap table-custom"
        @change="handleTableChange"
        :customRow="selectRowData"
        :rowClassName="setRowClass">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;object-fit: cover;" :preview="0"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>
        <!-- 产品图片 -->
        <template slot="productImageSlot" slot-scope="text, record">
          <div>
            <p>
              <span v-if="!record.productImage" style="font-size: 12px;font-style: italic;">无图片</span>
              <img v-else :src="getImgView(record.productImage)" style="width:80px;height: 80px;border-radius: 4px;object-fit: cover;cursor: pointer;" @click="handleImg(record.productImage)"/>
            </p>            
            <a-tag color="red" size="mini" v-if="record.violationTag && record.violationTag.level">{{ record.violationTag && record.violationTag.level }}星</a-tag>
            <p style="color: #1890FF; cursor: pointer; margin-top: 8px;" @click="handleSearchImg(record)">查重搜图</p>
          </div>
        </template>
        <!-- SKU/SPU -->
        <template slot="skuCodeSlot" slot-scope="text, record">
          <div>
            <!-- 多属性SKU,单属性SPU -->
            <p style="font-weight: 700;">{{ record.productType === '2' ? record.spuCode : record.skuCode}}</p>
            <!-- type 违规标签 1  注意标签 2 -->
            <p v-for="(item, index) in record.tagList" :key="index">
              <a-tag color="green" v-if="item.type === 2">{{ item.name }}</a-tag>
            </p>
            <p>
              <a-tag color="red" v-if="record.violationTag && record.violationTag.tagName">{{ record.violationTag && record.violationTag.tagName }}</a-tag>
            </p>
            <p>
              <a-tag color="#f5222d" v-if="record.shelfStatus === '2'">下架</a-tag>
            </p>
            <p>金义仓</p>
            <p :title="`开发人：${record.createBy}`">{{ record.createBy }}</p>
            <p v-if="record.supplier && record.supplier.supplier" :title="`采购人：${record.supplier.supplier.buyer}`">{{ record.supplier.supplier.buyer }}</p>
            <p :title="`审核人：${record.auditBy}`">{{ record.auditBy }}</p>
            <p>
              <a-tag color="#1890FF">{{ record.productStatus_dictText }}</a-tag>
              <a-tag color="#fdaa00" v-if="record.productType === '2'">SPU</a-tag>
              <a-tag color="#fdaa00" v-if="record.productType === '1'">SKU</a-tag>
            </p>
            <p>整款月销：{{ record.orderCount }}</p>
          </div>
        </template>
        <!-- 产品信息 -->
        <template slot="productTypeSlot" slot-scope="text, record">
          <div class="product-info">
            <p style="font-weight: 700; font-size: 14px;">{{ record.title }}</p>
            <p>产品类目：{{ record.categoryFullName }}</p>
            <p>
              <span>海关编码：</span>
              <span style="margin-left: 8px;">版型编码：{{ record.patternCode }}</span>
            </p>
            <p>
              <span>产品中文名称：{{ record.name }}</span>
              <span style="margin-left: 8px;">供应商货号：{{ record.supplierItemNum }}</span>
              <span style="margin-left: 8px;">报关中文名称：{{ record.customs && record.customs.nameCn }}</span>
              <span style="margin-left: 8px;">报关英文名称：{{ record.customs && record.customs.nameEn }}</span>
              <!-- <span style="margin-left: 8px;">申报中文名称：</span>
              <span style="margin-left: 8px;">申报英文名称：</span> -->
              <span style="margin-left: 8px;">报关价值：</span>
              <span style="margin-left: 8px;">重量(g)：{{ record.weight }}</span>
            </p>
            <p>
              <span>颜色：{{ record.colorDesc }}</span>
              <span style="margin-left: 8px;">尺寸：{{ record.size }}</span>
              <span style="margin-left: 8px;">包含：{{ record.includedItem }}</span>
              <span style="margin-left: 8px;">耗材：{{ record.customs && record.customs.materialCn }}</span>
              <span style="margin-left: 8px;">电池配置：{{ record.batteryConfig_dictText }}</span>
              <span style="margin-left: 8px;">保质期天数：</span>
              <span style="margin-left: 8px;">保质期剩余天数：</span>
              <span style="margin-left: 8px;">仓库加工费：</span>
              <span style="margin-left: 8px;">重量(g)：{{ record.weight }}</span>
              <span style="margin-left: 8px;">抛重(g)：{{ record.customs && record.customs.volumetricWeight }}</span>
              <span style="margin-left: 8px;">抛重比：{{ record.customs && record.customs.volumetricWeightRatio }}</span>
              <span style="margin-left: 8px;">长(cm)：{{ record.customs && record.customs.length }}</span>
              <span style="margin-left: 8px;">宽(cm): {{ record.customs && record.customs.width }}</span>
              <span style="margin-left: 8px;">高(cm)：{{ record.customs && record.customs.height }}</span>
              <span style="margin-left: 8px;">来料包装：{{ record.incomingPackage_dictText }}</span>
              <span style="margin-left: 8px;">出货包装：{{ record.protectPackage_dictText }}</span>
              <span style="margin-left: 8px;">英文材质：{{ record.customs && record.customs.materialEn }}</span>
              <span style="margin-left: 8px;">中文材质：{{ record.customs && record.customs.materialCn }}</span>
              <span style="margin-left: 8px;">面料克重：</span>
            </p>        
            <p style="color: red;">刊登次数：{{ record.exportCount }}</p>
            <p>
              <span>库存：</span>
              <span style="margin-left: 8px;">剩余库存：</span>
              <span style="margin-left: 8px;">创建时间：{{ record.createTime }}</span>
              <span style="margin-left: 8px;">SPU：{{ record.spuCode }}</span>
            </p>
            <p>产品来源：{{ record.source_dictText }}</p>
            <p style="color: red;">参考链接：{{ record.referenceLink }}</p>
            <p style="color: red;">备注：{{ record.remark }}</p>
            <p style="color: red;">违规原因：{{ record.violationTag && record.violationTag.reason }}</p>
            <p><span>所有站点定价：</span><span style="margin-left: 8px;">销售价：</span></p>
          </div>
        </template>
        <!-- 供应商信息 -->
        <template slot="supplierNameSlot" slot-scope="text, record" v-if="record.supplier">
          <div v-has="'ProductLibrarySkuList:supplierName'">
            <p>{{ record.supplier && record.supplier.supplierName }}</p>
            <p>供应商代码：{{ record.supplier && record.supplier.supplier && record.supplier.supplier.code }}</p>
            <p>采购员：{{ record.supplier && record.supplier.supplier && record.supplier.supplier.buyer }}</p>
            <p>状态：{{ getSupplierStatus(record) }}</p>
            <p>是否滞销可退：{{ getIsRetentionRefund(record) }}</p>
            <p>采购周期：{{ record.supplier && record.supplier.purchaseCycle }}</p>
            <p>回货率：{{ record.supplier && record.supplier.supplier && record.supplier.supplier.returnRate }}<span v-if="record.supplier && record.supplier.supplier && record.supplier.supplier.returnRate">%</span></p>
            <!-- <p>SKU价格：</p> -->
            <p>拿货价：{{ record.supplier && record.supplier.purchasePrice }}</p>
            <p>付款方式：{{ getPaymentMethod(record) }}</p>
            <p>90天退款率：{{ record.supplier && record.supplier.supplier && record.supplier.supplier.ninetyDayRefundRate }}<span v-if="record.supplier && record.supplier.supplier && record.supplier.supplier.ninetyDayRefundRate">%</span></p>
            <p>2年退款率：{{ record.supplier && record.supplier.supplier && record.supplier.supplier.twoYearRefundRate }}<span v-if="record.supplier && record.supplier.supplier && record.supplier.supplier.twoYearRefundRate">%</span></p>
            <p>采购链接：{{ record.supplier && record.supplier.purchaseLink }}</p>
            <p>备用采购链接</p>
          </div>
        </template>

        <span slot="action" slot-scope="text, record">
          <div>
            <a @click="handlePreview(record)">预览</a>
          </div>
          <div v-if="record.shelfStatus != '2' && handleAuthority(record, 'edit')" v-has="'ProductLibrarySkuList:edit'">
            <a @click="handleEdit(record)">编辑</a>
          </div>
          <div v-has="'ProductLibrarySkuList:UpperLowerFrame'">
            <a @click="handleUpdateShelfStatus(1, record)" v-if="record.shelfStatus === '2'">上架</a>
            <a @click="handleUpdateShelfStatus(2, record)" v-else>下架</a>
          </div>
          <div v-if="record.shelfStatus != '2'">
            <div v-if="handleAuthority(record, 'remark')" v-has="'ProductLibrarySkuList:edit'">
              <a @click="handleRemark(record)">备注</a>
            </div>
            <div v-has="'ProductLibrarySkuList:violationMark'">
              <a @click="handleViolationMark(record)">违规标记</a>
            </div>
            <div v-has="'ProductLibrarySkuList:uploadVideo'">
              <a @click="handleVideo(record, '上传视频')">上传视频</a>
            </div>
            <div v-has="'ProductLibrarySkuList:downloadVideo'">
              <a @click="handleVideo(record, '下载视频')">下载视频</a>
            </div>
            <div v-has="'ProductLibrarySkuList:downloadImages'">
              <a @click="handleDownloadImages(record)">下载图片包</a>
            </div>
            <!-- 仅可复制流程为：开发中、审批中、待编辑、已完成 的产品 -->
            <div v-if="record.productStatus === 1 || record.productStatus === 2 || record.productStatus === 3 || record.productStatus === 7" v-has="'ProductLibrarySkuList:copy'">
              <a @click="handleCopy(record)">复制</a>
            </div>
            <div v-has="'ProductLibrarySkuList:MSKU'" v-if="record.productStatus === 7">
              <a @click="handleMSKU(record)">MSKU</a>
            </div>
          </div>
          <!-- 操作日志 -->
          <div>
            <a><j-operate-log :id="record.id"></j-operate-log></a>
          </div>
        </span>
      </a-table>
    </div>

    <product-library-sku-modal class="detail-modal" ref="modalForm" @ok="modalFormOk"></product-library-sku-modal>
    <!-- 导出 -->
    <product-library-sku-export-modal ref="modalExportForm" @ok="modalFormOk"></product-library-sku-export-modal>
    <!-- 预览 -->
    <product-library-sku-preview-modal ref="modalPreviewForm" @ok="modalFormOk"></product-library-sku-preview-modal>
  </a-card>
</template>

<script>
  import Vue from 'vue'
  import { USER_INFO } from '@/store/mutation-types'
  import { getAction, postAction, putAction, postFormAction } from '@/api/manage'
  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import ProductLibrarySkuModal from './modules/ProductLibrarySkuModal'
  import ProductLibrarySkuExportModal from './modules/ProductLibrarySkuExportModal'
  import ProductLibrarySkuPreviewModal from './modules/ProductLibrarySkuPreviewModal'
  import { colAuthFilter } from "@/utils/authFilter"
  import { productMixins } from '@/views/productLibrary/mixins/productMixins'
  import JSZip from 'jszip'
  import FileSaver from 'file-saver'
  export default {
    name: 'ProductLibrarySkuChildList',
    mixins:[JeecgListMixin, mixinDevice, productMixins],
    components: {
      ProductLibrarySkuModal,
      ProductLibrarySkuExportModal,
      ProductLibrarySkuPreviewModal
    },
    data () {
      return {
        description: '产品库-违禁词管理页面',
        tagOptions: [],
        tagOptions_: [],
        queryParam_: {
          codeType: 1,
          tagIdsType: 1
        },
        buttonTagIds: '',
        disableMixinCreated: true,
        productSupplierStatusList: [],
        productSupplierPaymentMethodList: [],
        // 表头
        columns: [
          // {
          //   title: '#',
          //   dataIndex: '',
          //   key:'rowIndex',
          //   width:60,
          //   align:"center",
          //   customRender:function (t,r,index) {
          //     return parseInt(index)+1;
          //   }
          // },
          {
            title:'产品图片',
            align:"center",
            dataIndex: 'productImage',
            scopedSlots: { customRender: 'productImageSlot' }
          },
          {
            title:'SKU/SPU',
            align:"center",
            dataIndex: 'skuCode',
            scopedSlots: { customRender: 'skuCodeSlot' }
          },
          {
            title:'产品信息',
            align:"center",
            dataIndex: 'productType',
            width: 500,
            scopedSlots: { customRender: 'productTypeSlot' }
          },
          {
            title:'供应商信息',
            align:"center",
            dataIndex: 'supplierName',
            scopedSlots: { customRender: 'supplierNameSlot' }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        url: {
          list: "/hzkj-product/product/productLibrary/sku/list",
          delete: "/hzkj-product/product/productLibrary/sku/delete",
          deleteBatch: "/hzkj-product/product/productLibrary/sku/deleteBatch",
          exportXlsUrl: "/hzkj-product/product/productLibrary/sku/exportXls",
          importExcelUrl: "hzkj-product/product/productLibrary/sku/importMSKUExcel",
          tagList: "/hzkj-product/product/productLibrary/tag/list",
          tagQueryList: "/hzkj-product/product/productLibrary/tag/queryList",
          exportMSKUTemplatesXls: "/hzkj-product/product/productLibrary/sku/exportMSKUTemplatesXls",
          featureTag: "/hzkj-product/product/productLibrary/sku/featureTag",
          processChange: "/hzkj-product/product/productLibrary/sku/processChange",
          updateShelfStatus: "/hzkj-product/product/productLibrary/sku/updateShelfStatus",
          forbiddenWordList: '/hzkj-product/product/productLibrary/forbiddenWord/list',
          copy: "/hzkj-product/product/productLibrary/sku/copy",
          getDownloadImages: "/hzkj-product/product/productLibrary/sku/getDownloadImages"
        },
        dictOptions: [
          {
            text: "开发中",
            value: "1",
            vHas: 'ProductLibrarySkuList:development'
          },
          {
            text: "审批中",
            value: "2",
            vHas: 'ProductLibrarySkuList:review'
          },
          {
            text: "待编辑",
            value: "3",
            vHas: 'ProductLibrarySkuList:waitEdit'
          },
          {
            text: "待查重",
            value: "4",
            vHas: 'ProductLibrarySkuList:waitLook'
          },
          {
            text: "查违规",
            value: "5",
            vHas: 'ProductLibrarySkuList:violations'
          },
          {
            text: "待翻译",
            value: "6",
            vHas: 'ProductLibrarySkuList:translate'
          },
          {
            text: "已完成",
            value: "7",
            vHas: 'ProductLibrarySkuList:finished'
          }
        ],
        superFieldList: [],
        forbiddenWord: [],
      }
    },
    created() {
      this.getSuperFieldList();
      this.columns = colAuthFilter(this.columns,'ProductLibrarySkuList:');
      this.initDictConfig();

      this.loadData_('', 'queryMyCategory');
      this.tagList();
      this.tagQueryList();
      this.forbiddenWordList();

      this.getDictOptions();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      }
    },
    provide(){
      return {
        getProjectList: () => this.treeData,
        productSupplierStatusList: () => this.productSupplierStatusList,
        productSupplierPaymentMethodList: () => this.productSupplierPaymentMethodList,
        getForbiddenWord: () => this.forbiddenWord
      }
    },
    methods: {
      initDictConfig(){
      },
      selectRowData(record,index){
        const that = this
        return {
          on:{
            dblclick:() => {
              // this.handleDetail(record)
            }
          }
        }
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'word',text:'违禁词',dictCode:''})
        fieldList.push({type:'string',value:'description',text:'解释',dictCode:''})
        fieldList.push({type:'string',value:'createBy',text:'创建人',dictCode:''})
        this.superFieldList = fieldList
      },
      changeLoadData(categoryId){
        this.$set(this.queryParam_, 'categoryId', categoryId);
        this.queryParam.categoryId = categoryId;
        this.loadData();
      },
      handleDeteleParams(){
        delete this.queryParam.code;
        delete this.queryParam.codeType;
        delete this.queryParam.timeRange;
      },
      handleImg(text){
        if(text){
          this.$viewerApi({images: [text]});
        }
      },
      handleSearchImg(record){
        let productStatus = '';
        if(record.productStatus === '7'){
          productStatus = '1';
        }
        if(record.shelfStatus === '2'){
          productStatus = '2';
        }
        this.$router.push({
          path:'/productLibrary/ProductLibraryImgList',
          query:{ params: encodeURIComponent(JSON.stringify({
            imageUrl: record.productImage,
            categoryId: record.categoryId,
            productStatus
          })) }
        })   
      },
      setRowClass(record) {
        // 产品检查工具检测后，违规，背景F59A23
        if(record.customForbiddenWord){
          return "custom-forbiddenWord";
        }
        // 列表产品背景，若为下架产品背景为浅红色EC808D，若为SPU背景为浅黄色FACD91，SKU背景为白色
        if(record.shelfStatus === '2') {
          return "custom-rowClass";
        } else if(record.productType != '1') {
          return "custom-rowClass_";
        }
      },
      timeChange(time1, time2){
        this.queryParam_.beginTimeRange = time2 && time2[0];
        this.queryParam_.endTimeRange = time2 && time2[1];
      },
      searchQuery(){
        if(this.queryParam_.code && this.queryParam_.code.length < 3){
          this.$message.warning('SKU至少3位字符！');
          return;
        }
        if(this.queryParam_.codeType === 1){
          this.queryParam_.spuCode = this.queryParam_.code;
          this.queryParam_.skuCode = '';
        }else if(this.queryParam_.codeType === 2){
          this.queryParam_.skuCode = this.queryParam_.code;
          this.queryParam_.spuCode = '';
        }
        this.queryParam = Object.assign({}, this.queryParam_);
        this.handleDeteleParams();
        this.loadData(1);
      },
      searchReset(){
        this.$set(this.queryParam_, 'categoryId', '');
        this.handleCategoryIdChange('');
        this.queryParam_ = {
          categoryId: '',
          codeType: 1,
          tagIdsType: 1
        }
        this.queryParam = Object.assign({}, this.queryParam_);
        this.handleDeteleParams();
        this.loadData();
      },
      tagList(){
        // 获取实时注意标签
        let params = {
          column: 'createTime',
          order: 'desc',
          pageNo: 1,
          pageSize: 9999,
        }
        getAction(this.url.tagList, params).then((res) => {
          if(res.success){
            let tagOptions_ = (res.result && res.result.records) || [];
            tagOptions_ = tagOptions_.filter(item => item.type === 2);
            this.tagOptions_ = tagOptions_.map(item => {
              return {
                ...item,
                text: item.name,
                value: item.id
              }
            })
          }else{
            this.$message.warning(res.message);
          }
        })
      },
      tagQueryList(){
        // 获取历史注意标签，包括已经删除的
        getAction(this.url.tagQueryList).then((res) => {
          if(res.success){
            let tagOptions = res.result || [];
            this.tagOptions = tagOptions.map(item => {
              return {
                ...item,
                text: item.name,
                value: item.id
              }
            })
          }else{
            this.$message.warning(res.message);
          }
        })
      },
      handleExportCustom(){
        if(!(this.selectionRows && this.selectionRows.length)){
          this.$message.warning('请选择一条数据进行导出！');
          return;
        }
        if(this.selectionRows && this.selectionRows.length > 1){
          this.$message.warning('请选择一条数据进行导出！');
          return;
        }
        // 仅可导出已完成的产品
        let flag = this.selectionRows.some(item => item.productStatus != 7);
        if(flag){
          this.$message.warning('仅可导出已完成的产品');
          this.selectionRows = this.selectionRows.filter(item => item.productStatus === 7);
          this.selectedRowKeys = this.selectionRows.map(item => item.id) || [];
          return;
        }
        this.$refs.modalExportForm.edit(this.selectionRows[0]);
        this.$refs.modalExportForm.title = "导出";
        this.$refs.modalExportForm.disableSubmit = false;
      },
      handleViolationMark(record){
        this.$refs.modalExportForm.edit(record);
        this.$refs.modalExportForm.title = "违规标记";
        this.$refs.modalExportForm.disableSubmit = false;
      },
      handleRemark(record){
        this.$refs.modalExportForm.edit(record);
        this.$refs.modalExportForm.title = "备注";
        this.$refs.modalExportForm.disableSubmit = false;
      },
      handleMSKU(record){
        this.$refs.modalExportForm.edit(record);
        this.$refs.modalExportForm.title = "MSKU列表";
        this.$refs.modalExportForm.disableSubmit = true;
      },
      handleBlur(){
        if(!(this.buttonTagIds && this.buttonTagIds.length)) return;
        // 绑定特性标签
        if(!(this.selectedRowKeys && this.selectedRowKeys.length)){
          this.$message.warning('请选择一条数据！');
          return;
        }
        let params = {
          skuIdList: this.selectedRowKeys,
          tagIdList: this.buttonTagIds.split(',')
        }
        postAction(this.url.featureTag, params).then((res) => {
          if(res.success){
            this.$message.success(res.message);
            this.loadData();
            this.onClearSelected();
            this.buttonTagIds = '';
          }else{
            this.$message.warning(res.message);
          }
        })
      },
      handleProcessChange(d){
        if(!(this.selectedRowKeys && this.selectedRowKeys.length)){
          this.$message.warning('请选择一条数据！');
          return;
        }
        let flag = this.selectionRows.some(item => {
          return item.productStatus === 7 || item.shelfStatus === '2';
        });
        if(flag){
          this.$message.warning('已完成的产品、下架的产品禁止变更状态！');
          this.selectionRows = this.selectionRows.filter(item => !(item.productStatus === 7 || item.shelfStatus === '2'));
          this.selectedRowKeys = this.selectionRows.map(item => item.id);
          return;
        }
        let params = {
          productStatus: d.value,
          skuIdsList: this.selectedRowKeys
        }
        putAction(this.url.processChange, params).then((res) => {
          if(res.success){
            this.$message.success(res.message);
            this.loadData();
            this.onClearSelected();
          }else{
            this.$message.warning(res.message);
          }
        })
      },
      handleUpdateShelfStatus(shelfStatus, record){
        if(!record){
          if(!(this.selectedRowKeys && this.selectedRowKeys.length)){
            this.$message.warning('请选择一条数据！');
            return;
          }
        }
        let params = {
          shelfStatus,
          skuIdList: record ? [record.id] : this.selectedRowKeys
        }
        putAction(this.url.updateShelfStatus, params).then((res) => {
          if(res.success){
            this.$message.success(res.message);
            this.loadData();
            this.onClearSelected();
          }else{
            this.$message.warning(res.message);
          }
        })
      },
      handleVideo(record, title){
        this.$refs.modalExportForm.edit(record);
        this.$refs.modalExportForm.title = title;
        this.$refs.modalExportForm.disableSubmit = false;
      },
      forbiddenWordList(){
        let params = {
          column: 'createTime',
          order: 'desc',
          pageNo: 1,
          pageSize: 9999
        }
        getAction(this.url.forbiddenWordList, params).then((res) => {
          if(res.success){
            let forbiddenWord = (res.result && res.result.records) || [];
            this.forbiddenWord = forbiddenWord.map(item => item.word);
          }else{
            this.$message.warning(res.message);
          }
        })
      },
      handleProductInspectionTool(){
        let forbiddenIndex;
        if(!(this.selectedRowKeys && this.selectedRowKeys.length)){
          this.$message.warning('请选择一条数据！');
          return;
        }
        this.dataSource = this.dataSource.map((item, index) => {
          if(this.selectedRowKeys.indexOf(item.id) > -1){
            if(!item.description){
              return {
                ...item,
                customForbiddenWord: false
              }
            }
            let description = `${item.description.point1},${item.description.point2},${item.description.point3},${item.description.point4},${item.description.point5},${item.description.description}`;
            let customForbiddenWord = this.forbiddenWord.some(cur => description.indexOf(cur) > -1);
            // 待编辑状态变更为已完成
            if(!customForbiddenWord){
              if(item.productStatus === 6){
                this.handleProcessChange({ value:  7});
              }
            }else{
              // 获取第一条纯在违禁词的数据
              if(!(forbiddenIndex || forbiddenIndex == 0)){
                forbiddenIndex = index;
              }
            }
            return {
              ...item,
              customForbiddenWord
            }
          }else{
            return {
              ...item,
              customForbiddenWord: false
            }
          }
        })
        let forbiddenFlag = this.dataSource.some(item => item.customForbiddenWord);
        if(forbiddenFlag){
          this.$message.warning('产品存在违禁词！');
          try{
            let domList = document.querySelectorAll('.ant-table-scroll .ant-table-tbody>.ant-table-row');
            if(domList[forbiddenIndex]){
              domList[forbiddenIndex].scrollIntoView();
            }
          }catch(e){}
        }else{
          this.$message.success('产品不存在违禁词！');
        }
        this.onClearSelected();
      },
      handleAuthority(record, type){
        if(type === 'edit' || type === 'remark'){
          // 编辑
          let status = record.productStatus === 1 || record.productStatus === 3;
          let role = Vue.ls.get(USER_INFO).username === record.createBy;
          return status && role;
        }
      },
      async getImgArrayBuffer(url) {
        const response = await fetch(url);
        if (!response.ok) {
          throw new Error(`请求失败: ${response.status}`);
        }
        return await response.blob();
      },
      getDownloadImages(skuId){
        return new Promise((resolve, reject) => {
          getAction(this.url.getDownloadImages, { skuId }).then((res) => {
            if(res.success){
              resolve(res.result);
            }else{
              this.$message.warning(res.message);
            }
          })
        })
      },
      async handleDownloadImages(record){
        let downloadImages = await this.getDownloadImages(record.id);
        let imageList = downloadImages.imageList || [];
        imageList = imageList.map(item => {
          return {
            imageUrl: item.imageUrl
          }
        });
        let skuList = downloadImages.skuList || [];
        skuList.unshift({
          name: downloadImages.name,
          imageList
        });

        let flag = skuList.every(item => !(item.imageList && item.imageList.length));
        if(flag){
          this.$message.warning('暂无图片!');
          return;
        }

        const zip = new JSZip();
        const imgFolder = zip.folder(`${record.name} ${record.skuCode}`); // 创建一个文件夹存放图片
        try {
          await Promise.all(skuList.map(async (image) => {
            if(image.imageList && image.imageList.length){
              const typeFolder = imgFolder.folder(image.name); // 创建一个文件夹存放图片
              let imageList_ = image.imageList.map(m => m.imageUrl);
              await Promise.all(imageList_.map(async (url) => {
                const response = await fetch(url);
                if (!response.ok){
                  this.$message.warning('下载失败！');
                  return;
                }
                const blob = await response.blob();
                typeFolder.file(url.split('/').pop(), blob); // 将图片添加到ZIP
              }));
            }
          }))
          const content = await zip.generateAsync({ type: 'blob' });
          FileSaver.saveAs(content, `${record.name} ${record.skuCode}`); 
        } catch (error) {	           
          this.$message.warning('下载失败！');    
        }
      },
      handleCopy(record){
        postFormAction(this.url.copy, { skuId: record.id }).then((res) => {
          if(res.success){
            this.$message.success(res.message);
            this.loadData();
            window.scrollTo({
              top: 0
            })
          }else{
            this.$message.warning(res.message);
          }
        })
      },
      handlePreview(record){
        this.$refs.modalPreviewForm.edit(record);
        this.$refs.modalPreviewForm.title = "预览";
        this.$refs.modalPreviewForm.disableSubmit = true;
      },
      async getDictOptions(){
        this.productSupplierStatusList = await this.initDictData('product_supplier_status');
        this.productSupplierPaymentMethodList = await this.initDictData('product_supplier_payment_method');
      },
      getSupplierStatus(record){
        if(!(record.supplier && record.supplier.supplier && record.supplier.supplier.supplierStatus)) return '';
        return (this.productSupplierStatusList.find(item => item.value == record.supplier.supplier.supplierStatus) || {}).text;
      },
      getIsRetentionRefund(record){
        if(record.supplier && record.supplier.supplier && record.supplier.supplier.isRetentionRefund === '1'){
          return '是';
        }else if(record.supplier && record.supplier.supplier && record.supplier.supplier.isRetentionRefund === '0'){
          return '否';
        }
        return '';
      },
      getPaymentMethod(record){
        if(!(record.supplier && record.supplier.supplier && record.supplier.supplier.paymentMethod)) return '';
        return (this.productSupplierPaymentMethodList.find(item => item.value == record.supplier.supplier.paymentMethod) || {}).text;
      },
      handleCategoryIdChange(val){
        this.$emit('handleCategoryIdChange', val);
      },
      handleChange(){
        let isViolation = this.queryParam_.isViolation ? false : true;
        this.$set(this.queryParam_, 'isViolation', isViolation);
      },
      handleChange_(){
        let statusType = this.queryParam_.statusType === '1' ? '' : '1';
        this.$set(this.queryParam_, 'statusType', statusType);
      }
    }
  }
</script>

<style>
.custom-rowClass{
  background-color: #F8D2D7;
}
.custom-rowClass_{
  background-color: #FACD91;
}
.custom-forbiddenWord{
  background-color: #F59A23;
}
</style>
<style scoped lang="less">
  @import '~@assets/less/common.less';
  /deep/.ant-form-item-children{
    display: flex;
    align-items: center;
  }
  .table-custom{
    /deep/.ant-table-scroll .ant-table-tbody{
      td:not(:first-child){
        text-align: left !important;
        vertical-align: top;
      }
    }
  }
  .product-info{
    width: 100%;
    p{
      white-space: normal;
    }
  }
</style>